package com.cmpan.networkdisk.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;


/**
 * ClassName:ExceptionHandler
 * Package:com.cmpan.networkdisk.handler
 * Description:
 *
 * @Date:2020/7/6 16:23
 * @com.chuangmei
 */
@ControllerAdvice
public class HandlerException {

    //日志输出
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request,Exception exception) throws Exception{

        //打印异常信息
        logger.error("Request URL : {},Exception : {}",request.getRequestURL(),exception);

        //如果状态码不为null,抛出异常,交给springboot处理,否则,跳转到自定义的error界面
        if (AnnotationUtils.findAnnotation(exception.getClass(), ResponseStatus.class) != null) {
            throw exception;
        }

        //ModelAndView
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("url",request.getRequestURL());
        modelAndView.addObject("exception",exception);

        modelAndView.setViewName("error/error");

        return modelAndView;

    }

}
